package cn.miju.admin.framework.exception;

import cn.miju.admin.framework.content.CodeMessage;
import cn.miju.admin.framework.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.StringJoiner;

/**
 * <pre>
 * 统一异常处理
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-01 15:23
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {
    /**
     * 系统异常处理
     * @param e 系统异常
     * @return 结果
     */
    @ExceptionHandler(Exception.class)
    public Object apiException(Exception e){
        log.error("系统异常拦截！", e);
        if (e instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) e;
            if (serviceException.getStatus() != HttpStatus.OK) {
                HttpStatus httpStatus = serviceException.getStatus();
                return ResponseEntity.status(httpStatus).body(Result.fail(CodeMessage.FAIL.getCode(),
                        CodeMessage.FAIL.getMessage() + httpStatus.value() + ":" + httpStatus.getReasonPhrase()));
            }
            return Result.fail(serviceException.getCode(), serviceException.getMessage());
        } else if (e instanceof BindException) {
            BindingResult bindingResult;
            if (e instanceof MethodArgumentNotValidException) {
                bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            } else {
                bindingResult = ((BindException) e).getBindingResult();
            }
            StringJoiner stringJoiner = new StringJoiner("，","【", "】");
            if (bindingResult.hasFieldErrors()) {
                bindingResult.getFieldErrors().forEach(fieldError -> {
                    stringJoiner.add(fieldError.getDefaultMessage());
                });
            }
            if (stringJoiner.length() > 0) {
                return Result.fail(CodeMessage.VALIDATE_FAIL.getCode(), stringJoiner.toString());
            }
            return Result.fail(CodeMessage.VALIDATE_FAIL.getCode(), e.getMessage());
        } else if (e instanceof SQLException || e instanceof BadSqlGrammarException) {
            return Result.fail(CodeMessage.SQL_FAIL);
        }
        return Result.fail(CodeMessage.FAIL.getCode(), CodeMessage.FAIL.getMessage() + e.getMessage());
    }

}
